<script setup>
import axios from 'axios';
import { ref } from 'vue'
import { useUrlStore } from '@/stores/url';
const UrlStore = useUrlStore()
import { showDialog } from 'vant';
import { showSuccessToast, showFailToast } from 'vant';
import { useRouter } from 'vue-router'

const router = useRouter()


//测试数据
// const studentId = ref('2022441010221')
// const name = ref('卢贝宸')
// const gender = ref('1') //0是男，1是女
// const grade = ref('2022') //数字型，只能是4位数字
// const major = ref('网络空间安全')
// const classNumber = ref('2') //字符串型，只能是一位数字
// const phone = ref('13407976823')
// const wxName = ref('与手机同号')
// const reason = ref('多认识几个大佬')
// const introduce = ref('我是前端小白')
// const experience = ref('个人经历（此处省略200字）')
// const prize = ref('2023数学建模省一')
// const remark = ref('')
// const photo = ref('')

const studentId = ref('')
const name = ref('')
const gender = ref('0') //0是男，1是女
const grade = ref('') //数字型，只能是4位数字
const major = ref('')
const classNumber = ref('') //字符串型，只能是一位数字
const phone = ref('')
const wxName = ref('')
const reason = ref('')
const introduce = ref('')
const experience = ref('')
const prize = ref('')
const remark = ref('')
const photo = ref('')

import { check } from '@/apis/testAPI';

check().then(res => {
  if (res.data.code == 1200) {
    //如果用户没有登录，指向动态登录界面
    var a = document.createElement('a');
    a.setAttribute('href', 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdadd0122365919e8&scope=snsapi_userinfo&response_type=code&redirect_uri=http://175.178.62.164:61803/wxuser/getSignUpUserInfo?url=/resume&expires_in=3600#wechat_redirect');
    a.setAttribute('target', '_blank');
    a.setAttribute('id', 'redict');
    // 防止反复添加
    if (document.getElementById('redict')) {
      document.body.removeChild(document.getElementById('redict'));
    }
    document.body.appendChild(a);
    a.click();
  }
}).catch(err => {
  console.log(err);
})

//顶部图片
const imageUrl = ref('');
const imgRef = ref(null);

axios({
  url: 'http://175.178.62.164:61803/config/real'
}).then(result => {
  const photoSrc = result.data.data.deliverPhoto;
  imageUrl.value = UrlStore.url + '/' + photoSrc;
}).catch(err => {
  console.dir(err);
});

//为了避免在图片尚未加载完成时显示"图片加载失败"，给 img 元素添加一个 hidden 类来将其隐藏，等图片加载完成之后再将其移除
const onImageLoad = () => {
  imgRef.value.classList.remove('hidden');
};


//上传证件照
const fileList = ref([]);
const afterRead = (file) => {
  // 此时可以自行将文件上传至服务器
  const formData1 = new FormData();
  formData1.append('photo', file.file);
  axios({
    url: 'http://175.178.62.164:61803/studentinfo/picture',
    method: 'post',
    data: formData1,
  }).then(result => {
    photo.value = result.data.data
  }).catch(err => {
    console.dir(err);
  })
}

//保存草稿
const saveSevice = () => {
  if (grade.value.trim() != '') {
    if (!(+grade.value == grade.value) || grade.value.length != 4 || +grade.value < 2010 || +grade > 2030) {
      showDialog({
        message: '请输入符合要求的年级！例如：2023',
      }).then(() => {
        // on close
      });
      return
    }
  }

  if (classNumber.value.trim() != '') {
    if (!(+classNumber.value == classNumber.value) || classNumber.value.length > 2) {
      showDialog({
        message: '请输入符合要求的班号！例如：1',
      }).then(() => {
        // on close
      });
      return
    }
  }

  let formData = new window.FormData();
  formData.append("studentId", studentId.value)
  formData.append("name", name.value)
  formData.append("gender", gender.value)
  formData.append("grade", grade.value)
  formData.append("major", major.value)
  formData.append("classNumber", classNumber.value)
  formData.append("phone", phone.value)
  formData.append("wxName", wxName.value)
  formData.append("reason", reason.value)
  formData.append("introduce", introduce.value)
  formData.append("experience", experience.value)
  formData.append("prize", prize.value)
  formData.append("remark", remark.value)
  formData.append("photo", photo.value)
  axios({
    url: 'http://175.178.62.164:61803/studentinfo/save',
    method: 'post',
    data: formData,
  }).then(result => {
    // console.dir(result);
    // console.log(result.data.code);
    if (result.data.code === 0) {
      showSuccessToast('保存成功！');
    } else {
      showFailToast('保存失败！');
    }
  }).catch(err => {
    console.dir(err);
  })
}

//查询草稿
const text = ref('提交简历')
axios({
  url: 'http://175.178.62.164:61803/studentinfo/select'
}).then(result => {
  // console.dir(result);
  // console.log(result.data.data.studentInfo.id);
  // console.log(result.data.data.isSubmit);
  if (result.data.data.isSubmit) {
    text.value = '修改简历'
  } else {
    text.value = '提交简历'
  }
  studentId.value = result.data.data.studentInfo.studentId
  name.value = result.data.data.studentInfo.name
  gender.value = String(result.data.data.studentInfo.gender)
  grade.value = result.data.data.studentInfo.grade
  major.value = result.data.data.studentInfo.major
  classNumber.value = result.data.data.studentInfo.classNumber
  phone.value = result.data.data.studentInfo.phone
  wxName.value = result.data.data.studentInfo.wxName
  reason.value = result.data.data.studentInfo.reason
  introduce.value = result.data.data.studentInfo.introduce
  experience.value = result.data.data.studentInfo.experience
  prize.value = result.data.data.studentInfo.prize
  remark.value = result.data.data.studentInfo.remark
  photo.value = result.data.data.studentInfo.photo

  //证件照回显
  if (photo.value != '') {
    fileList.value.push({
      url: UrlStore.url + '/' + photo.value
    })
  }
}).catch(err => {
  console.dir(err);
})

//提交简历
const submitService = () => {
  //以下一堆全是判空操作和表单校验
  if (studentId.value.trim() === '') {
    showDialog({
      message: '请输入学号！',
    }).then(() => {
      // on close
    });
    return
  }

  if (name.value.trim() === '') {
    showDialog({
      message: '请输入姓名！',
    }).then(() => {
      // on close
    });
    return
  }

  if (grade.value.trim() === '') {
    showDialog({
      message: '请输入年级！',
    }).then(() => {
      // on close
    });
    return
  }

  if (major.value.trim() === '') {
    showDialog({
      message: '请输入专业！',
    }).then(() => {
      // on close
    });
    return
  }

  if (classNumber.value.trim() === '') {
    showDialog({
      message: '请输入班号！',
    }).then(() => {
      // on close
    });
    return
  }

  if (classNumber.value.trim() === '') {
    showDialog({
      message: '请输入班号！',
    }).then(() => {
      // on close
    });
    return
  }

  if (phone.value.trim() === '') {
    showDialog({
      message: '请输入电话号码！',
    }).then(() => {
      // on close
    });
    return
  }

  if (wxName.value.trim() === '') {
    showDialog({
      message: '请输入微信号！',
    }).then(() => {
      // on close
    });
    return
  }

  if (introduce.value.trim() === '') {
    showDialog({
      message: '请输入个人介绍！',
    }).then(() => {
      // on close
    });
    return
  }

  if (reason.value.trim() === '') {
    showDialog({
      message: '请输入加入AchoBeta的理由！',
    }).then(() => {
      // on close
    });
    return
  }

  if (experience.value.trim() === '') {
    showDialog({
      message: '请输入个人经历！',
    }).then(() => {
      // on close
    });
    return
  }

  if (prize.value.trim() === '') {
    showDialog({
      message: '请输入获奖情况！',
    }).then(() => {
      // on close
    });
    return
  }

  if (photo.value.trim() === '') {
    showDialog({
      message: '请上传证件照！',
    }).then(() => {
      // on close
    });
    return
  }
  if (!(+grade.value == grade.value) || grade.value.length != 4 || +grade.value < 2010 || +grade > 2030) {
    showDialog({
      message: '请输入符合要求的年级！例如：2023',
    }).then(() => {
      // on close
    });
    return
  }

  if (!(+classNumber.value == classNumber.value) || classNumber.value.length > 2) {
    showDialog({
      message: '请输入符合要求的班号！例如：1',
    }).then(() => {
      // on close
    });
    return
  }

  let formData = new window.FormData();
  formData.append("studentId", studentId.value)
  formData.append("name", name.value)
  formData.append("gender", gender.value)
  formData.append("grade", +grade.value)
  formData.append("major", major.value)
  formData.append("classNumber", classNumber.value)
  formData.append("phone", phone.value)
  formData.append("wxName", wxName.value)
  formData.append("reason", reason.value)
  formData.append("introduce", introduce.value)
  formData.append("experience", experience.value)
  formData.append("prize", prize.value)
  formData.append("remark", remark.value)
  formData.append("photo", photo.value)

  //保存草稿
  axios({
    url: 'http://175.178.62.164:61803/studentinfo/save',
    method: 'post',
    data: formData,
  }).then(result => {
    // console.dir(result);
    // console.log(result.data.code);
  }).catch(err => {
    console.dir(err);
  })

  //提交简历
  axios({
    url: 'http://175.178.62.164:61803/studentinfo/submit',
    method: 'post',
    data: formData
  }).then(result => {
    // console.dir(result);
    // console.log(result.data.code);
    if (result.data.code === 0) {
      router.push('/feedBack-FB')
    }
  }).catch(err => {
    console.dir(err);
  })
}

//上传附件与显示附件草稿
const fileList1 = ref([])
const fileInput = ref(null)

//附件回显
axios({
    url: 'http://175.178.62.164:61803/attachment/list'
  }).then(result=>{
    for(let i=0;i<result.data.data.length;i++){
      fileList1.value.push({
        name:result.data.data[i].remark
      })
    }
  })

//增加附件
const handleFileChange = () => {
  const files = fileInput.value.files
  const formdata = new FormData()
  for (let i = 0; i < files.length; i++) {
    fileList1.value.push(files[i])
    formdata.append('attachment', files[i])
  }
  axios({
    url: 'http://175.178.62.164:61803/attachment/submit',
    method: 'post',
    data: formdata
  }).then(result => {
    console.log(result)
  }).catch(err => {
    console.log(err)
  })
}

//删除附件
const deleteFile = async (index) => {
  fileList1.value.splice(index, 1)
  //获取附件列表
  const pObj = await axios({
    url: 'http://175.178.62.164:61803/attachment/list'
  })

  const pId = pObj.data.data[index].id

  axios({
    url:'http://175.178.62.164:61803/attachment/delete',
    params:{
      id:pId
    }
  })
}

//提交给后台
const submitFile = () => {
  const formdata = new FormData()
  for (let i = 0; i < fileList1.value.length; i++) {
    console.log(fileList1.value[i]);
    formdata.append('attachment', fileList1.value[i])
  }
  axios({
    url: 'http://175.178.62.164:61803/attachment/submit',
    method: 'post',
    data: formdata
  }).then(result => {
    console.log(result)
  }).catch(err => {
    console.log(err)
  })
}
</script>

<template>
  <div class="bigBox">
    <img ref="imgRef" alt="图片加载失败！" class="bgcImg hidden" @load="onImageLoad" :src="imageUrl">
    <div class="title">AchoBeta实验室简历投递</div>

    <!-- 轻提示：提示用户保存草稿成功或失败 -->
    <van-toast v-model:show="show" style="padding: 0">
      <template #message>
        <van-image :src="image" width="200" height="140" style="display: block" />
      </template>
    </van-toast>

    <!-- 弹窗：在用户提交简历时进行表单校验和判空 -->
    <van-dialog v-model:show="show" show-cancel-button>
    </van-dialog>

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="studentId" name="学号" label="学号" placeholder="学号"
          :rules="[{ required: true, message: '请填写学号' }]" required=true />

        <van-field v-model="name" name="姓名" label="姓名" placeholder="姓名" :rules="[{ required: true, message: '请填写姓名' }]"
          required=true />

        <van-field name="radio" label="性别" required=true>
          <template #input>
            <van-radio-group v-model="gender" direction="horizontal">
              <van-radio name="0">男</van-radio>&nbsp;&nbsp;&nbsp;
              <van-radio name="1">女</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field v-model="grade" name="年级" label="年级" placeholder="年级（例如：2023）"
          :rules="[{ required: true, message: '请填写年级' }]" required=true />

        <van-field v-model="major" name="专业" label="专业" placeholder="专业" :rules="[{ required: true, message: '请填写专业' }]"
          required=true />

        <van-field v-model="classNumber" name="班号" label="班号" placeholder="班号（例如：1）"
          :rules="[{ required: true, message: '请填写班号' }]" required=true />

        <van-field v-model="phone" name="手机号码" label="手机号码" placeholder="手机号码"
          :rules="[{ required: true, message: '请填写手机号码' }]" required=true />

        <van-field v-model="wxName" name="微信号" label="微信号" placeholder="微信号"
          :rules="[{ required: true, message: '请填写微信号' }]" required=true />

        <van-field v-model="introduce" rows="2" autosize label="个人介绍（自我认知）" type="textarea" placeholder="请输入个人介绍（自我认知）"
          required=true />

        <van-field v-model="reason" rows="2" autosize label="加入AchoBeta的理由" type="textarea" placeholder="请输入加入AchoBeta的理由"
          required=true />

        <van-field v-model="experience" rows="2" autosize label="个人经历（项目经历、职业规划等）" type="textarea"
          placeholder="请输入个人经历（项目经历、职业规划等）" required=true />

        <van-field v-model="prize" rows="2" autosize label="获奖情况" type="textarea" placeholder="请输入获奖情况" required=true />

        <div class="box" style="display: flex;">
          <div class="redStar">*</div>
          <div class="font">证件照</div>
          <van-uploader v-model="fileList" :after-read="afterRead" :max-count=1 :deletable=false :reupload=true />
        </div>

        <div class="box">
          <div class="redStar" style="font-size: 12px;">简历模板下载：<a
              href="https://pan.baidu.com/s/121Qy7us9pYOhEldhGQan1Q?pwd=803m">https://pan.baidu.com/s/121Qy7us9pYOhEldhGQan1Q?pwd=803m</a>
            提取码：803m</div>
        </div>

        <div class="box">
          <div class="font">作品附件</div>
          <!-- <br>
          <br> -->
          <div class="file-upload">
            <input type="file" multiple id="upload" class="inputfile" ref="fileInput" @change="handleFileChange">
            <label for="upload">
              <span>选择文件</span>
            </label>
            <div class="file-list">
              <div v-for="(file, index) in fileList1" :key="index" class="file-item">
                <span class="file-name">{{ file.name }}</span>
                <span class="delete-icon" @click="deleteFile(index)">×</span>
              </div>
            </div>
          </div>
        </div>

        <van-field v-model="remark" rows="2" autosize label="备注" type="textarea" placeholder="请输入备注" />
      </van-cell-group>

      <div class="buttonBox">
        <van-button plain type="primary" @click="saveSevice">保存草稿</van-button>
        <van-button type="primary" @click="submitService" :text=text></van-button>
      </div>

    </van-form>
  </div>
</template>

<style scoped>
* {
  padding: 0;
  margin: 0;
}

.hidden {
  display: none;
}

.bigBox {
  background-image: linear-gradient(#4993fa,
      #9dc6ff,
      #a0e4f1,
      #f1fafb);
}

.title {
  width: 375px;
  height: 75px;
  line-height: 75px;
  text-align: center;
  font-size: 20px;
  font-weight: 700;
}

.bgcImg {
  width: 375px;
}

.van-cell.van-field {
  width: 325px;
  margin: 20px;
}

.van-cell-group.van-cell-group--inset {
  width: 350px;
  margin: 0 auto;
  border-radius: 20px;
}

.van-field__control {
  width: 320px;
}

.van-button {
  width: 120px;
}

.buttonBox {
  padding: 30px 0 30px 0;

  display: flex;
  justify-content: space-around;
}

.redStar {
  display: inline-block;
  font-size: 14px;
  color: red;
}

.inputfile {
  opacity: 0;
  width: 0.1px;
  height: 0.1px;
  position: absolute;
  top: 0;
  left: 0;
}

.inputfile+label {
  color: #fff;
  background-color: rgb(25, 137, 250);
  padding: 10px 20px;
  cursor: pointer;
  display: inline-block;
  border-radius: 3px;
  font-size: 14px;
}

.file-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}

.file-item {
  display: flex;
  align-items: center;
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 4px 8px;
  font-size: 14px;
  background-color: #eee;
  border-radius: 4px;
}

.file-name {
  max-width: 320px;
  word-break: break-all;
}

.delete-icon {
  margin-left: 10px;
  cursor: pointer;
}

.font {
  display: inline-block;
  font-size: 14px;
  padding: 0 20px 10px 0;
}

.box {
  margin: 10px 0;
  padding: 0 20px;
}
</style>